package com.hctforgreen.greenservice;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import com.hctforgreen.greenservice.ctr.DbController;
import com.hctforgreen.greenservice.ctr.HctController;
import com.hctforgreen.greenservice.model.CheckVersionEntity;
import com.hctforgreen.greenservice.model.MachineListEntity.MachineEntity;
import com.hctforgreen.greenservice.service.TechnicalDataUpdateService;
import com.hctforgreen.greenservice.ui.adapter.MainV3ListAdapter;
import com.hctforgreen.greenservice.ui.widget.PullToRefreshListView;
import com.hctforgreen.greenservice.utils.DownloadBookLstInitFinishUtil;
import com.hctforgreen.greenservice.utils.HctConstants;
import com.hctforgreen.greenservice.utils.HctResult;
import com.hctforgreen.greenservice.utils.LogUtil;
import com.hctforgreen.greenservice.utils.VersionDialogUtil;
import com.hctforgreen.greenservice.utils.VersionUtil;

import java.util.List;

import ca.laplanete.mobile.pageddragdropgrid.PagedDragDropGrid;
import cn.jpush.android.api.JPushInterface;

/**
 * 主页(使用PullToRefreshListView改写版本)
 *
 * @author Tallen Zhai
 */
public class MainActivityV2 extends ParentActivity {
    private final String TAG = "MainActivityV2";

    private String CURRENT_PAGE_KEY = "CURRENT_PAGE_KEY";
    private String DROP_GRID_KEY = "DROP_GRID_KEY";
    public final static int REQUEST_UPDATE_MSG = 0x119;
    public final static String UPADTE_PERSON_POINTS_ACTION_NAME = "upadte_person_points_action_name";
    public final static String SWITCH_LANGUAGE_ACTION_NAME = "switch_language_action_name";
    private long mLExitTime = 0;
    private static final long mLDelayTime = 2000;
    public static final int ZXING_DATA = 3024;

    private MainV3ListAdapter mAdapter;
    private MainActivityV2 mSelf;
    private UpadtePersonPointsReceiver mPersonPointsReceiver;
    private SwitchLanguageReceiver mLanguageReceiver;

    private int pingCount;
    private boolean isCloudServer;
    //后台操作数据库的Service名
    private final String SERVICE_NAME = "com.hctforgreen.greenservice.service.TechnicalDataUpdateService";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        LogUtil.e(TAG, "onCreate");
        super.onCreate(savedInstanceState);
        super.rightScroll = false;//取消父类的右滑返回动作
        setContentView(R.layout.activity_main_v2);
        JPushInterface.init(getApplicationContext());
        // dealTopBannerParams();
        //
        // initTitleButtonBar();
        // initWindow();
        mSelf = this;
        pingCount = getIntent().getIntExtra("PING_COUNT", 0);
        isCloudServer = getIntent().getBooleanExtra("WHICH_SERVER", false);
        /*if(!HctBackTestJsonController.isB_DEBUG()){
            Log.i("DATA", "传到MainActivityV2的--pingCount   " + pingCount);
			Log.i("DATA", "传到MainActivityV2的--isClounServer   " + isCloudServer);
		}*/

        initWindowV2();

        final String sVersionName = VersionUtil.getAppVersionName(this);
        loadVersionStatus(sVersionName);

        jpushJump();
        initUpdatePointsReciever();
        initSwitchLanguageReciever();
    }

    /**
     * jpush通知进入 key:cn.jpush.android.MSG_ID, value:876493625 key:app,
     * value:com.hctforgreen.greenservice key:cn.jpush.android.ALERT,
     * value:管理员已回复您提交的反馈："all"。
     * key:cn.jpush.android.NOTIFICATION_CONTENT_TITLE, value:格力掌上通
     * key:cn.jpush.android.EXTRA, value:{}
     * key:cn.jpush.android.NOTIFICATION_ID, value:876493625
     */
    private void jpushJump() {
        Bundle bundle = getIntent().getExtras();
        if (bundle == null) {
            return;
        }
        String value = bundle.getString("cn.jpush.android.ALERT");
        if (value != null && value.trim().length() > 0) {// 反馈回复通知
            Log.w("cn.jpush.android.ALERT", value);
            if (value.contains("管理员已回复您提交的反馈")) {
                Intent intent = new Intent(this, MyFeedbackActivity.class);
                intent.putExtra("fromMain", true);
                startActivity(intent);
            } else if (value.contains("资料有更新了，快去下载吧！")) {// 资料有更新通知
                Intent intent = new Intent(this, DownloadManagerActivityV2.class);
                intent.putExtra("fromMain", true);
                startActivity(intent);
            } else if (value.contains("视频有更新了，快去看看吧！")) {// 视频有更新通知
                Intent intent = new Intent(this, VideoTypesActivity.class);
                intent.putExtra("fromMain", true);
                startActivity(intent);
            } else {
                Intent intent = new Intent();
                intent.putExtra("fromMain", true);
                intent.setClass(this, MessageFirstActivityV2.class);
                startActivityForResult(intent, mSelf.REQUEST_UPDATE_MSG);
            }
        } else if (!bundle.containsKey("loginout_phone") && !bundle.containsKey("assignLogin")) {
            Intent intent = new Intent();
            intent.putExtra("fromMain", true);
            intent.setClass(this, MessageFirstActivityV2.class);
            startActivityForResult(intent, mSelf.REQUEST_UPDATE_MSG);
        }
    }

    private void initWindowV2() {
        View convertView = findViewById(R.id.lyt_parent);
        PullToRefreshListView listView = (PullToRefreshListView) convertView.findViewById(R.id.lst_default_list);
        mAdapter = new MainV3ListAdapter(MainActivityV2.this, listView, mSelf, pingCount, isCloudServer);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            doubleTouchExit();
            return true;
        } else {
            return false;
        }
    }

    private void doubleTouchExit() {
        if ((System.currentTimeMillis() - mLExitTime) > mLDelayTime) {
            Toast.makeText(MainActivityV2.this, getString(R.string.double_touch_exit_title) + getString(R.string.app_name),
                    Toast.LENGTH_SHORT).show();
            mLExitTime = System.currentTimeMillis();
        } else {
            LogUtil.e(TAG, "onKeyDown");
            /**
             * 20161215 ---390694添加停止更新资料服务
             * 不放在onDestory()里，onDestory()方法有时候不执行
             */
            Intent intent = new Intent(mSelf, TechnicalDataUpdateService.class);
            stopService(intent);
            LogUtil.e(TAG, "结束TechnicalDataUpdateService服务");
            if (!DownloadBookLstInitFinishUtil.getDownloadBookFinished(mSelf)) {
                DownloadBookLstInitFinishUtil.saveUpdateBookServiceFinished(mSelf, false);
                LogUtil.i(TAG, "333333333333333333333333333");
            } else {
                DownloadBookLstInitFinishUtil.saveUpdateBookServiceFinished(mSelf, false);
                LogUtil.i(TAG, "444444444444444444444444444");
            }
            //stopService(new Intent(TechnicalDataUpdateService.MY_NAME));
            finish();
            System.exit(0);
        }

    }

    @Override
    protected void onNewIntent(Intent intent) {
        // String finishMain = getIntent().getStringExtra(
        // HctConstants.FINISH_MIAN_START_LOGIN);
        // if (HctConstants.FINISH_MIAN_START_LOGIN.equals(finishMain)) {
        // startActivity(new Intent(MainActivity.this, LoginActivity.class));
        // finish();
        // return;
        // }
        super.onNewIntent(intent);
        setIntent(intent);
        if (mAdapter != null) {
            Log.w("onNewIntent____mAdapter.getDragDropGrid()",
                    mAdapter.getDragDropGrid() + ","
                            + mAdapter.getMenuAdapter());
        }
    }

    @Override
    protected void onResume() {
        LogUtil.e(TAG, "onResume");
        super.onResume();
        if (HctConstants.isFinish_mian_start_login()) {
            HctConstants.setFinish_mian_start_login(false);
            String loginoutPhone = HctConstants.getLoginout_phone();
            HctConstants.setLoginout_phone(null);
            Intent intent = new Intent(this, LoginActivity.class);
            intent.putExtra("loginout_phone", loginoutPhone);
            startActivity(intent);
            finish();
            return;
        }
        jpushJump();
        JPushInterface.onResume(this);
        initSkinLayout();
        if (mAdapter != null) {
            Log.w("onResume______mAdapter.getDragDropGrid()",
                    mAdapter.getDragDropGrid() + ","
                            + mAdapter.getMenuAdapter());
        }
        //2017-1-3  390694
        // 若程序闪退，则将判断服务是否在执行插入数据库操作的偏好设置赋值为false；防止重新进入页面时提示正在更新数据库
        if (!isServiceWork(mSelf, SERVICE_NAME)) {
            LogUtil.i("DATA", "TechnicalDataUpdateService服务没有启动");
            DownloadBookLstInitFinishUtil.saveUpdateBookServiceFinished(mSelf, false);
        }
    }

    /**
     * 检查服务是否在后台运行
     */
    public boolean isServiceWork(Context mContext, String serviceName) {
        boolean isWork = false;
        ActivityManager myAM = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> runningServiceInfos = myAM.getRunningServices(40);
        if (runningServiceInfos.size() <= 0) {
            return false;
        }
        for (int i = 0; i < runningServiceInfos.size(); i++) {
            String mName = runningServiceInfos.get(i).service.getClassName().toString();

            if (mName.equals(serviceName)) {
                isWork = true;
                break;
            }
        }
        return isWork;
    }


    @Override
    protected void onPause() {
        LogUtil.e(TAG, "onPause");
        super.onPause();
        JPushInterface.onPause(this);
        if (mAdapter != null) {
            Log.w("onPause_____mAdapter.getDragDropGrid()",
                    mAdapter.getDragDropGrid() + ","
                            + mAdapter.getMenuAdapter());
        }
    }

    /**
     * 扫描回调
     * <p>
     * 未读消息数更新
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        if (requestCode == REQUEST_UPDATE_MSG) {// 通知中心返回
            mAdapter.updateMsgCount(false);
            mAdapter.notifyDataSetChanged();
        } else {
            String result = data.getStringExtra("result");
            startTechnicalDataMutliLevelActivity(result);
        }

    }

    private void startTechnicalDataMutliLevelActivity(String result) {
        String sUserInput = result.trim();
        if (sUserInput.equals("")) {
            return;
        }
        DbController dbController = new DbController(MainActivityV2.this);
        MachineEntity machineEntity = dbController.getMachineEntity(sUserInput);
        if (machineEntity == null) {
            Toast.makeText(MainActivityV2.this,
                    R.string.edit_input_select_is_null, Toast.LENGTH_SHORT)
                    .show();
            return;
        }
        Intent intent = new Intent();
        intent.setClass(MainActivityV2.this, DebugBooksActivity.class);
        intent.putExtra(HctConstants.ON_ACTIVITY_KEY_MACHINE_ENTITY,
                machineEntity);
        startActivity(intent);
    }

    private void loadVersionStatus(final String versionCode) {

        @SuppressLint("HandlerLeak") final Handler handler = new Handler() {
            public void handleMessage(Message msg) {

                HctResult hctResult = new HctResult();
                switch (msg.what) {
                    case HctConstants.STATUS_SUCCESS:
                        hctResult = (HctResult) msg.obj;
                        CheckVersionEntity entity = (CheckVersionEntity) hctResult.data;
                        if (entity.isNew.equals("true")) {
                            //Log.i("hh", entity.isNew+"");
                            return;
                        }
                        /**
                         * 强制更新
                         */
                        if (entity.updateFlag.equals("Enforce")) {
                            VersionDialogUtil versionDialogUtil = new VersionDialogUtil();
                            versionDialogUtil.updateVersionEnforceDialog(
                                    MainActivityV2.this, entity);
                        }
                        /**
                         * 推荐更新
                         */
                        else if (entity.updateFlag.equals("")
                                || entity.updateFlag.equals("Recommend")) {
                            VersionDialogUtil versionDialogUtil = new VersionDialogUtil();
                            versionDialogUtil.updateVersionRecommendDialog(
                                    MainActivityV2.this, entity);
                        }
                        /**
                         * 忽略更新
                         */
                        else if (entity.updateFlag.equals("Ignore")) {
                            //Log.i("hh", "忽略更新");
                        }
                        break;
                    case HctConstants.STATUS_FAILD:
                        break;
                }
            }

        };

        new Thread() {
            public void run() {
                Message message = new Message();
                try {
                    HctController controller = new HctController(MainActivityV2.this);
                    HctResult result = controller.checkVersion(versionCode);
                    if (result.status == HctConstants.STATUS_SUCCESS) {
                        message.what = result.status;
                        message.obj = result;
                    } else {
                        message.what = HctConstants.STATUS_FAILD;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                handler.sendMessage(message);
            }
        }.start();
    }

    @Override
    protected void onDestroy() {
        LogUtil.e(TAG, "onDestroy");
        /**
         * 20160323 ---390694屏蔽
         */
        //stopService(new Intent(mSelf, WifiUpdateService.class));
        //stopService(new Intent(WifiUpdateService.MY_NAME));
        unregisterReceiver(mPersonPointsReceiver);
        unregisterReceiver(mLanguageReceiver);
        super.onDestroy();
    }

    private void initUpdatePointsReciever() {
        mPersonPointsReceiver = new UpadtePersonPointsReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(UPADTE_PERSON_POINTS_ACTION_NAME);
        registerReceiver(mPersonPointsReceiver, filter);
    }

    public class UpadtePersonPointsReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            mAdapter.renderPersionPointsTv();
        }
    }

    private void initSwitchLanguageReciever() {
        mLanguageReceiver = new SwitchLanguageReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(SWITCH_LANGUAGE_ACTION_NAME);
        registerReceiver(mLanguageReceiver, filter);
    }

    public class SwitchLanguageReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            finish();
        }
    }

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        int savedPage = savedInstanceState.getInt(CURRENT_PAGE_KEY);
        PagedDragDropGrid gridview = mAdapter.getDragDropGrid();
        if (gridview != null) {
            gridview.restoreCurrentPage(savedPage);
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        PagedDragDropGrid gridview = mAdapter.getDragDropGrid();
        if (gridview != null) {
            outState.putInt(CURRENT_PAGE_KEY, gridview.currentPage());
        }
        super.onSaveInstanceState(outState);
    }
}
